// 个股异动Vue组件
const StockAlertComponent = {
    template: `
        <div class="stock-alert-page">
            <div class="page-header">
                <h2>个股异动</h2>
                <div class="header-actions">
                    <el-button @click="refreshStockList" :loading="loadingStocks" size="small">
                        <i class="el-icon-refresh"></i>
                        刷新列表
                    </el-button>
                </div>
            </div>

            <div class="stock-panel-layout">
                <div class="stock-list-panel">
                    <div class="panel-header">
                        <h3 class="panel-title">股票列表</h3>
                        <div class="panel-actions">
                            <el-tag type="info" v-if="selectedStock" size="small">
                                当前: {{ selectedStock.name }} ({{ selectedStock.code }})
                            </el-tag>
                        </div>
                    </div>
                    
                    <div class="search-input">
                        <el-input
                            v-model="stockSearchQuery"
                            placeholder="搜索股票代码/名称/拼音首字母"
                            clearable
                            @input="handleStockSearch">
                            <i slot="prefix" class="el-icon-search"></i>
                        </el-input>
                    </div>
                    <div class="stock-table-container">
                        <el-table
                            :data="paginatedStockList"
                            style="width: 100%"
                            height="calc(80vh - 200px)"
                            stripe
                            v-loading="loadingStocks"
                            @row-click="handleStockClick"
                            :row-class-name="getTableRowClass">
                            
                            <el-table-column prop="code" label="代码" width="80" sortable>
                                <template #default="scope">
                                    <span class="stock-code" @click.stop="selectStock(scope.row)">
                                        {{ scope.row.code }}
                                    </span>
                                </template>
                            </el-table-column>
                            
                            <el-table-column prop="name" label="名称" width="120" sortable>
                                <template #default="scope">
                                    <span class="stock-name">{{ scope.row.name }}</span>
                                </template>
                            </el-table-column>
                            
                            <el-table-column prop="pinyin" label="拼音" width="80">
                                <template #default="scope">
                                    <span v-if="scope.row.pinyin" class="stock-pinyin">{{ scope.row.pinyin }}</span>
                                </template>
                            </el-table-column>
                            
                            <el-table-column label="状态" width="80">
                                <template #default="scope">
                                    <el-tag v-if="selectedStock && selectedStock.code === scope.row.code" 
                                           type="success" size="mini">已选</el-tag>
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- 股票列表分页 -->
                        <div class="pagination-wrapper">
                            <el-pagination
                                @size-change="handleStockSizeChange"
                                @current-change="handleStockCurrentChange"
                                :current-page="stockCurrentPage"
                                :page-sizes="[20, 50, 100, 200]"
                                :page-size="stockPageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="filteredStockList.length"
                                small>
                            </el-pagination>
                        </div>
                    </div>
                </div>

                <div class="stock-detail-panel">
                    <div v-if="selectedStock" class="alert-data-container">
                        <div class="panel-header">
                            <h3 class="panel-title">{{ selectedStock.name }} ({{ selectedStock.code }})</h3>
                            <div class="panel-actions">
                                <el-button size="small" @click="refreshAlertData" :loading="loading">
                                    <i class="el-icon-refresh"></i>
                                    刷新
                                </el-button>
                            </div>
                        </div>

                        <!-- 统计信息 -->
                        <div class="statistics-info" v-if="stockAlertData.length > 0">
                            <el-row :gutter="20">
                                <el-col :span="6">
                                    <el-card class="stat-card">
                                        <div class="stat-title">异动记录</div>
                                        <div class="stat-value">{{ stockAlertData.length }}</div>
                                    </el-card>
                                </el-col>
                                <el-col :span="6">
                                    <el-card class="stat-card">
                                        <div class="stat-title">涉及板块</div>
                                        <div class="stat-value">{{ getUniqueBlockCount() }}</div>
                                    </el-card>
                                </el-col>
                                <el-col :span="6">
                                    <el-card class="stat-card">
                                        <div class="stat-title">平均次数</div>
                                        <div class="stat-value">{{ getAverageRiseCount() }}</div>
                                    </el-card>
                                </el-col>
                                <el-col :span="6">
                                    <el-card class="stat-card">
                                        <div class="stat-title">更新时间</div>
                                        <div class="stat-value">{{ lastUpdateTime }}</div>
                                    </el-card>
                                </el-col>
                            </el-row>
                        </div>

                        <!-- 异动数据表格 -->
                        <div class="alert-table" v-if="stockAlertData.length > 0">
                            <el-table
                                :data="paginatedAlertData"
                                style="width: 100%"
                                stripe
                                border
                                v-loading="loading"
                                height="calc(80vh - 350px)">
                                
                                <el-table-column prop="date" label="日期" width="100" sortable>
                                    <template #default="scope">
                                        <span>{{ formatDate(scope.row.date) }}</span>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="block" label="板块" width="120">
                                    <template #default="scope">
                                        <el-tag type="primary" size="mini">{{ scope.row.block }}</el-tag>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="reason" label="异动原因" min-width="150">
                                    <template #default="scope">
                                        <span>{{ scope.row.reason || '-' }}</span>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="sharesRange" label="股份范围" width="100">
                                    <template #default="scope">
                                        <span>{{ scope.row.sharesRange || '-' }}</span>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="num" label="数量" width="80">
                                    <template #default="scope">
                                        <span>{{ scope.row.num || '-' }}</span>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="day" label="连板" width="60">
                                    <template #default="scope">
                                        <el-tag v-if="scope.row.day" type="success" size="mini">
                                            {{ scope.row.day }}天
                                        </el-tag>
                                        <span v-else>-</span>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="edition" label="版数" width="60">
                                    <template #default="scope">
                                        <el-tag v-if="scope.row.edition" type="warning" size="mini">
                                            {{ scope.row.edition }}版
                                        </el-tag>
                                        <span v-else>-</span>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="totalRiseCount" label="上涨次数" width="100" sortable>
                                    <template #default="scope">
                                        <span style="color: #67c23a; font-weight: bold;">
                                            {{ scope.row.totalRiseCount || 0 }}
                                        </span>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column label="操作" width="80" fixed="right">
                                    <template #default="scope">
                                        <el-button type="text" size="mini" @click="viewDetail(scope.row)">
                                            详情
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <!-- 异动数据分页 -->
                            <div class="pagination-wrapper">
                                <el-pagination
                                    @size-change="handleAlertSizeChange"
                                    @current-change="handleAlertCurrentChange"
                                    :current-page="alertCurrentPage"
                                    :page-sizes="[10, 20, 50, 100]"
                                    :page-size="alertPageSize"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="stockAlertData.length"
                                    small>
                                </el-pagination>
                            </div>
                        </div>

                        <!-- 空状态 -->
                        <div v-else-if="!loading" class="welcome-panel">
                            <el-empty description="该股票暂无异动数据" :image-size="120">
                                <el-button type="primary" size="small" @click="refreshAlertData">
                                    <i class="el-icon-refresh"></i>
                                    重新查询
                                </el-button>
                            </el-empty>
                    </div>

                    <div v-else class="welcome-panel">
                        <el-empty description="请从左侧选择股票查看异动数据" :image-size="120">
                            <template #image>
                                <i class="el-icon-document" style="font-size: 48px; color: #c0c4cc;"></i>
                            </template>
                        </el-empty>
                    </div>
                </div>
            </div>
        </div>
    `,
    
    data() {
        return {
            loading: false,
            loadingStocks: false,
            lastUpdateTime: new Date().toLocaleString(),
            selectedStock: null,
            stockList: [],
            filteredStockList: [],
            stockAlertData: [],
            
            // 股票列表分页
            stockCurrentPage: 1,
            stockPageSize: 50,
            
            // 异动数据分页
            alertCurrentPage: 1,
            alertPageSize: 20,
            
            // 搜索
            stockSearchQuery: ''
        }
    },
    
    computed: {
        paginatedStockList() {
            const start = (this.stockCurrentPage - 1) * this.stockPageSize;
            const end = start + this.stockPageSize;
            return this.filteredStockList.slice(start, end);
        },
        
        paginatedAlertData() {
            const start = (this.alertCurrentPage - 1) * this.alertPageSize;
            const end = start + this.alertPageSize;
            return this.stockAlertData.slice(start, end);
        }
    },
    
    methods: {
        async loadStockList() {
            this.loadingStocks = true;
            try {
                const response = await axios.get('/api/stock-alert/stocks');
                console.log('股票列表API响应:', response.data);
                
                if (response.data && response.data.code === 200) {
                    this.stockList = response.data.data || [];
                    this.filteredStockList = [...this.stockList];
                    console.log('成功加载股票列表:', this.stockList.length, '只股票');
                } else if (Array.isArray(response.data)) {
                    this.stockList = response.data;
                    this.filteredStockList = [...this.stockList];
                    console.log('成功加载股票列表:', this.stockList.length, '只股票');
                } else {
                    console.error('股票列表数据格式异常:', response.data);
                    this.filteredStockList = [];
                }
            } catch (error) {
                console.error('加载股票列表失败:', error);
                this.filteredStockList = [];
                if (window.ElMessage) {
                    window.ElMessage.error('股票列表加载失败: ' + (error.response?.data?.message || error.message));
                }
            } finally {
                this.loadingStocks = false;
            }
        },
        
        async loadStockAlertData(stockCode) {
            if (!stockCode) {
                console.error('股票代码为空');
                return;
            }
            
            this.loading = true;
            try {
                const response = await axios.get(`/api/stock-alert/${stockCode}`);
                console.log('个股异动数据API响应:', response.data);
                
                if (response.data && response.data.code === 200) {
                    this.stockAlertData = response.data.data || [];
                    console.log('成功加载个股异动数据:', this.stockAlertData.length, '条记录');
                    this.alertCurrentPage = 1; // 重置到第一页
                    this.lastUpdateTime = new Date().toLocaleString();
                } else if (Array.isArray(response.data)) {
                    this.stockAlertData = response.data;
                    console.log('成功加载个股异动数据:', this.stockAlertData.length, '条记录');
                    this.alertCurrentPage = 1;
                    this.lastUpdateTime = new Date().toLocaleString();
                } else {
                    console.error('个股异动数据格式异常:', response.data);
                    this.stockAlertData = [];
                }
            } catch (error) {
                console.error('加载个股异动数据失败:', error);
                this.stockAlertData = [];
                if (window.ElMessage) {
                    window.ElMessage.error('数据加载失败: ' + (error.response?.data?.message || error.message));
                }
            } finally {
                this.loading = false;
            }
        },
        
        // 选择股票
        async handleStockClick(stock) {
            console.log('选择股票:', stock);
            this.selectedStock = stock;
            await this.loadStockAlertData(stock.code);
        },
        
        // 选择股票（表格行点击）
        async selectStock(stock) {
            await this.handleStockClick(stock);
        },
        
        // 搜索股票列表
        handleStockSearch() {
            const query = this.stockSearchQuery.trim().toLowerCase();
            
            if (!query) {
                this.filteredStockList = [...this.stockList];
                this.stockCurrentPage = 1;
                return;
            }
            
            this.filteredStockList = this.stockList.filter(stock => {
                return stock.code.toLowerCase().includes(query) ||
                       stock.name.toLowerCase().includes(query) ||
                       (stock.pinyin && stock.pinyin.toLowerCase().includes(query));
            });
            
            this.stockCurrentPage = 1; // 重置到第一页
            
            console.log('搜索结果:', this.filteredStockList.length, '条记录');
        },
        
        // 清空搜索
        clearStockSearch() {
            this.stockSearchQuery = '';
            this.handleStockSearch();
        },
        
        // 刷新股票列表
        async refreshStockList() {
            await this.loadStockList();
            this.handleStockSearch(); // 重新应用搜索过滤
            if (window.ElMessage) {
                window.ElMessage.success('股票列表已刷新');
            }
        },
        
        // 刷新当前选中股票的异动数据
        async refreshAlertData() {
            if (this.selectedStock) {
                await this.loadStockAlertData(this.selectedStock.code);
                if (window.ElMessage) {
                    window.ElMessage.success('异动数据已刷新');
                }
            } else {
                if (window.ElMessage) {
                    window.ElMessage.warning('请先选择股票');
                }
            }
        },
        
        // 股票列表分页处理
        handleStockSizeChange(newSize) {
            this.stockPageSize = newSize;
            this.stockCurrentPage = 1;
        },
        
        handleStockCurrentChange(newPage) {
            this.stockCurrentPage = newPage;
        },
        
        // 异动数据分页处理
        handleAlertSizeChange(newSize) {
            this.alertPageSize = newSize;
            this.alertCurrentPage = 1;
        },
        
        handleAlertCurrentChange(newPage) {
            this.alertCurrentPage = newPage;
        },
        
        // 查看详情
        viewDetail(row) {
            this.selectedDetail = row;
            this.detailDialogVisible = true;
        },
        
        handleDetailClose() {
            this.detailDialogVisible = false;
            this.selectedDetail = null;
        },
        
        // 格式化涨跌幅
        formatChangeRate(rate) {
            if (rate === null || rate === undefined || rate === 0) return '-';
            const value = parseFloat(rate);
            const color = value > 0 ? '#f56c6c' : value < 0 ? '#67c23a' : '#909399';
            const prefix = value > 0 ? '+' : '';
            return `<span style="color: ${color}">${prefix}${value.toFixed(2)}%</span>`;
        },
        
        // 获取唯一板块数量
        getUniqueBlockCount() {
            const blocks = new Set(this.stockAlertData.map(item => item.block).filter(block => block));
            return blocks.size;
        },
        
        // 获取平均次数
        getAverageRiseCount() {
            if (this.stockAlertData.length === 0) return 0;
            const total = this.stockAlertData.reduce((sum, item) => sum + (item.totalRiseCount || 0), 0);
            return (total / this.stockAlertData.length).toFixed(1);
        },
        
        // 格式化日期
        formatDate(dateStr) {
            if (!dateStr) return '-';
            return dateStr.substring(0, 10);
        },
        
        // 格式化时间
        formatTime(dateStr) {
            if (!dateStr) return '-';
            return dateStr.substring(11, 19);
        },
        
        // 获取表格行样式
        getTableRowClass({row, rowIndex}) {
            if (this.selectedStock && row.code === this.selectedStock.code) {
                return 'selected-row';
            }
            return '';
        }
    },
    
    mounted() {
        this.loadStockList();
    }
};